package com.example.capsule_kafka.service;

import com.example.capsule_kafka.bean.RoomBean;
import com.example.capsule_kafka.mapper.MacAddressToFieldMapper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhuzhiming
 * @Date: 2022/5/2 0:07
 */
@Service
public class FieldToMacService {

    @Resource
    MacAddressToFieldMapper macAddressToFieldMapper;
    @Resource
    RoomService roomBeanService;
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    public String getFieldByMac(String macAddress) {

        String field = macAddressToFieldMapper.getFieldByMac(macAddress);

        if (field == null) {
            return "";
        }

        if (redisTemplate.opsForValue().get(field) != null) {
            System.out.println("从redis获取.....");
            return redisTemplate.opsForValue().get(field);
        }

        List<RoomBean> roomBeanList = roomBeanService.getRoomListByField(field);
        String roomBeanJson = new Gson().toJson(roomBeanList);
        redisTemplate.opsForValue().set(field, roomBeanJson, 30, TimeUnit.MINUTES);
        System.out.println("从mysql获取.....");
        return roomBeanJson;

    }

}
